#include "user_BasicUserInformation.h"

LIST_HEAD(user_BUIF_list);

void add_employee(const char *name, char *phone, char *Gender,char* RandomNumber)
{
    user_BUIF *newuser = malloc(sizeof(user_BUIF));
    if (!newuser)
    {
        perror("内存分配失败");
        return;
    }

    strncpy(newuser->name, name, sizeof(newuser->name) - 1);
    strncpy(newuser->phone, phone, sizeof(newuser->phone) - 1);
    strncpy(newuser->name, Gender, sizeof(newuser->Gender) - 1);
    strncpy(newuser->RandomNumber, RandomNumber, sizeof(newuser->RandomNumber) - 1);
    // 初始化链表节点并添加到链表尾部
    INIT_LIST_HEAD(&newuser->list);
    list_add_tail(&newuser->list, &user_BUIF_list);
}
int write_employees_to_file(const char *name, char *phone, char *Gender,char* RandomNumber)
{
    FILE *file = fopen("/lvgl_yiyuan/user_BasicUserInformation.txt", "a+");
    // FILE *file = fopen("./user_BasicUserInformation.txt", "a+");
    if (!file)
    {
        perror("无法打开文件");
        return 0;
    }

    struct list_head *pos;
    user_BUIF *newuser;

    // 遍历链表并写入每个用户信息
    list_for_each(pos, &user_BUIF_list)
    {
        newuser = list_entry(pos, user_BUIF, list);
        fprintf(file, "姓名:%s\n", name);
        fprintf(file, "手机号:%s\n", phone);
        fprintf(file, "性别:%s\n", Gender);
        fprintf(file, "就诊卡号:%s\n", RandomNumber);
        fprintf(file, "-----------------\n");
    }

    fclose(file);
    return 1;
}

// 释放链表内存
void free_employee_list() 
{
    struct list_head *pos, *tmp;
    user_BUIF *newuser;
    
    list_for_each_safe(pos, tmp, &user_BUIF_list) {
        newuser = list_entry(pos, user_BUIF, list);
        list_del(pos);
        free(newuser);
    }
}